package com.bianhua.entity;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.bianhua.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Component
public class StudentDataListener extends AnalysisEventListener<StudentExcel> {

    @Autowired
    private StudentService studentService;

    private static final int BATCH_COUNT = 1000;
    List<StudentExcel> list = new ArrayList<StudentExcel>();

    private StudentExcel studentExcel;

    public StudentDataListener() {
        studentExcel = new StudentExcel();
    }

    public StudentDataListener(StudentExcel studentExcel) {
        this.studentExcel = studentExcel;
    }

    @Override
    public void invoke(StudentExcel data, AnalysisContext context) {
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }



    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

    private void saveData() {
        for (StudentExcel excel : list) {
            Student student = new Student();
            BeanUtils.copyProperties(excel,student);
            student.setAccount(student.getPhone());
            student.setPassword("123456");
            studentService.create(student);
        }
        list.clear();
    }
}
